package com.bit.springbook.interceptor;


import com.bit.springbook.constant.Constant;
import com.bit.springbook.model.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private ObjectMapper objectMapper;

    // true 就执行 false 就不执行
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("方法执行前");
        HttpSession session = request.getSession();
        if (session.getAttribute(Constant.USER_SESSION_KEY) == null) {
            response.getOutputStream().write(objectMapper.writeValueAsString(Result.fail("用户未登录")).getBytes());
            response.setStatus(401); // 用户未登录
            return false;
        }
        return true;
    }

//    @Override
//    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//        log.info("方法执行后");
//        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
//    }

//    @Override
//    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        log.info("视图处理完成后");
//        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
//    }
}
